import DaxieAdaptor from '../dexieAdaptor'

const db = new DaxieAdaptor()

db.init()

// setInterval(async () => {
//   console.log(await db.getAll())
// }, 3000)

const pool = []

let canInsert = true

onmessage = async function (event) {
  switch (event.data.action) {
    case 'QUERY':
      const result = await db.query({
        timestamp: event.data.data
      })

      postMessage({
        type: 'QUERY_RESULT',
        data: result
      })
      break
    case 'INSERT':
      pool.push(event.data.data)

      if (!canInsert) {
        return
      }

      if (pool.length > 0) {
        canInsert = false

        let tmp = [...pool]
        pool.length = 0

        console.log('save ', tmp.length, ' item')
        console.time('save')
        await db.insertMany(tmp)
        console.timeEnd('save')

        tmp = null

        canInsert = true
      }
      break
    default:
      break
  }
}
